package com.study.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import com.study.task.TaskRedisConfig;
import com.study.util.RedisUtil;

import redis.clients.jedis.Jedis;

@Aspect
@Component
@EnableAspectJAutoProxy
public class TaskAop {
	
	@Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)")
	public void pointcut(){}
	
	/*@Before("pointcut()")
	public void taskBefore(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println(methodName);
		Method method = (Method)joinPoint.getThis();
		//Method method = (Method)joinPoint.getTarget();
		if(method.isAnnotationPresent(TaskRedisConfig.class)) {
			System.out.println("aaaaaaaaaa---------");
		}
	}*/
	@Around("pointcut()")
	public void taskBefore(ProceedingJoinPoint joinPoint) throws Throwable {
		String methodName = joinPoint.getSignature().getName();
		System.out.println(methodName);
		MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();   
		Method method = methodSignature.getMethod();
		if(method.isAnnotationPresent(TaskRedisConfig.class)) {
			TaskRedisConfig tc = method.getAnnotation(TaskRedisConfig.class);
			String index = tc.index();
			Jedis jedis = RedisUtil.getJedis();
			jedis.select(Integer.parseInt(index));
			String key = tc.key();
			String value = tc.value();
			String timeout = tc.timeout();
			boolean isConcurrent = tc.isConcurrent();
			if(!isConcurrent) {
				//设置成功，返回 1 。 设置失败，返回 0 。
				long result = jedis.setnx(key, value);
				if(result==1) {
					long exresult = jedis.expire(key, Integer.parseInt(timeout));
					joinPoint.proceed();
					jedis.close();
				}else {
					return;
				}
			}
			
		}
	}

}
